﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

// vedi :
// http://www.codeproject.com/KB/cs/ProcessStartDemo.aspx
// http://msdn.microsoft.com/it-it/library/system.diagnostics.process.standardinput.aspx

namespace Algoritmi
{
    public abstract class ExternalExecutable : IAlgorithm
    {

        private Process executable;
        private StreamWriter stdInput;
        private StreamReader stdOutput;
        private StreamReader stdError;
        private string executableFileName;
        private string args;

        public ExternalExecutable(string executableFileName)
        {
            this.executableFileName = executableFileName;
            executable = new Process();
            executable.StartInfo.FileName = executableFileName;
            executable.StartInfo.UseShellExecute = false;
            executable.StartInfo.RedirectStandardInput = true;
            executable.StartInfo.RedirectStandardOutput = true;
            executable.StartInfo.RedirectStandardError = true;
            executable.StartInfo.ErrorDialog = false;
            executable.StartInfo.CreateNoWindow = true;
        }

        #region IAlgorithm Members

        public void setParams(object[] parameters)
        {
            args = "";
            foreach (object arg in parameters)
            {
                if (args != "")
                    args += " ";
                args += arg.ToString();
            }
        }

        public void ignorePhase()
        {
            executable.StartInfo.Arguments = args;
            executable.Start();
            stdInput = executable.StandardInput;
            stdError = executable.StandardError;
            stdOutput = executable.StandardOutput;
            string fineFase = stdOutput.ReadLine();
            
        }

        public void runPhase()
        {
            stdInput.WriteLine();
            string fineFase = stdOutput.ReadLine();
            executable.WaitForExit();
            executable.Close();
        }

        public abstract object[] getParameters(int step);

        public abstract int steps();

        public abstract string[] getParametersNames();

        #endregion
    }
}
